package com.archgeek.java.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import java.util.HashMap;

/**
 * @author pizhihui
 * @date 2023-03-01
 */
public class JavaNioTest {
    public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("1", "1");
    }
    private Selector selector = Selector.open();

    public JavaNioTest() throws IOException {
    }

    @Test
    public void testServerInit() throws IOException {

        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.bind(new InetSocketAddress(2888));
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        int ready = selector.select();
        if (ready > 0) {
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                boolean acceptable = key.isAcceptable();
                boolean readable = key.isReadable();
                boolean writable = key.isWritable();
                boolean valid = key.isValid();
                if (acceptable) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socket = channel.accept();
                    socket.configureBlocking(false);
                    socket.socket().setTcpNoDelay(true);
                    socket.socket().setKeepAlive(true);
                    socket.socket().setSendBufferSize(1024 * 1000);

                    // socket.register(selector)
                }

            }

        }


        SocketChannel socket = serverChannel.accept();

    }

    @Test
    public void testClientInit() {

    }


}
